/*
 * @Author: liuyonghu
 * @Date: 2021-08-10 15:24:17
 * @LastEditTime: 2021-08-10 16:24:14
 * @LastEditors: liuyonghu
 * @Description:
 * @FilePath: /miniprogram/submodule/YHCNetWoking.js
 */
class YHCNetWoking {
  constructor(options) {
    if (!options || !options.env) {
      return console.error(
        EvalError("- YHCNetWoking : Must has a env to config !")
      );
    }
    this.env = options.env;
    this.traceUser = options.traceUser;
    this.url = true;
    this.requestInterceptor = null;
    (!!options && !!options.requestInterceptor) && (this.requestInterceptor = options.requestInterceptor);
    this.resInterceptor = null;
    (!!options && !!options.resInterceptor) && (this.resInterceptor = options.resInterceptor);


    this.init();
  }
  //

  init() {
    wx.cloud.init({
      env: this.env,
      traceUser: this.traceUser,
    });
  }

  request(options) {
    if (this.requestInterceptor) {
      options =  this.requestInterceptor(options);
    }
    
    const { env, name, data } = options;
    const config = !env ? { env } : null;

    if (!!!data || !!!data.type) {
      return console.error(
        EvalError("- YHCNetWoking : Must has a type to request !")
      );
    }

    if (!!!name) {
      return console.error(
        EvalError("- YHCNetWoking : Must has a name to request !")
      );
    }

    return new Promise((resolve, reject) => {
      wx.cloud
        .callFunction({
          name,
          config,
          data,
        })
        .then((resp) => {
          if (this.resInterceptor) {
            
         
            return resolve(this.resInterceptor(resp));
          }
            resolve(resp);
        })
        .catch((e) => {
            reject(e);
        });
    });
  }
}

module.exports = YHCNetWoking;
